package com.xujie.sportsmeeting.listener;

import com.xujie.sportsmeeting.entity.EventRegistration;
import com.xujie.sportsmeeting.event.RegistrationAuditPassedEvent;
import com.xujie.sportsmeeting.service.EventRegistrationService;
import com.xujie.sportsmeeting.service.impl.EventCheckinServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 报名审核事件监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RegistrationAuditEventListener {

    private final EventRegistrationService eventRegistrationService;
    private final EventCheckinServiceImpl eventCheckinServiceImpl;

    /**
     * 监听报名审核通过事件，自动创建检录记录
     */
    @EventListener
    @Async
    public void handleRegistrationAuditPassed(RegistrationAuditPassedEvent event) {
        try {
            log.info("收到报名审核通过事件: registrationId={}, eventId={}, athleteId={}", 
                    event.getRegistrationId(), event.getEventId(), event.getAthleteId());
            
            // 获取报名记录
            EventRegistration registration = eventRegistrationService.getById(event.getRegistrationId());
            if (registration == null) {
                log.warn("报名记录不存在: registrationId={}", event.getRegistrationId());
                return;
            }
            
            // 创建检录记录
            boolean success = eventCheckinServiceImpl.createCheckinRecordForRegistration(registration);
            if (success) {
                log.info("审核通过事件处理成功，检录记录已创建: registrationId={}", event.getRegistrationId());
            } else {
                log.warn("审核通过事件处理失败，检录记录创建失败: registrationId={}", event.getRegistrationId());
            }
            
        } catch (Exception e) {
            log.error("处理报名审核通过事件时发生异常: registrationId={}", event.getRegistrationId(), e);
        }
    }
}
